package com.cyh.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.cyh.blog.business.service.BizArticleService;
import com.cyh.blog.business.service.BizCommentService;
import com.cyh.blog.business.service.SysLinkService;
import com.cyh.blog.business.vo.CommentVo;
import com.cyh.blog.business.vo.QQInfo;
import com.cyh.blog.exception.CustomException;
import com.cyh.blog.persistence.beans.BizArticle;
import com.cyh.blog.persistence.beans.BizComment;
import com.cyh.blog.persistence.beans.SysLink;
import com.cyh.blog.util.Result;
import com.github.pagehelper.PageInfo;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api")
public class RestApiController {

    private final String QQ_URL = "http://r.pengyou.com/fcg-bin/cgi_get_portrait.fcg?uins=";

    private final Integer PAGE_SIZE = 10;

    @Autowired
    private BizCommentService bizCommentService;

    @Autowired
    private BizArticleService bizArticleService;

    @Autowired
    private SysLinkService sysLinkService;

    /**
     * 获取qq信息
     * @param number
     * @return
     */
    @PostMapping("/qqInfo")
    public Result qqInfo(String number) throws IOException {

        QQInfo qqInfo = new QQInfo();
        String info = "失败";
        qqInfo.setNumber(number);
        qqInfo.setNikeName("匿名");
        qqInfo.setZone("");
        qqInfo.setEmail("");
        qqInfo.setHeadImg("");

        if (number != null){
            String url = QQ_URL + number;
            Document document = Jsoup.parse(new URL(url).openStream(), "GBK", url);
            String str = "\\[.*?\\]";
            Pattern p = Pattern.compile(str);
            Matcher m = p.matcher(document.toString());
            if (m.find()) {
                String[] split = m.group(0).split(",");
                if (split.length == 8) {
                    qqInfo.setHeadImg(split[0].substring(2, split[0].length()-1));
                    qqInfo.setNikeName(split[6].substring(1, split[6].length()-1));
                    qqInfo.setEmail(number + "@qq.com");
                    String zone = "http://" + number + ".qzone.qq.com ";
                    qqInfo.setZone(zone);
                    info = "成功";
                }
            }
        }
        String data = JSONObject.toJSONString(qqInfo);
        return Result.success(info).add("data", data);
    }


    /**
     * 用户提交 comment
     * @return
     */
    @PostMapping("/comment")
    public Result comment(QQInfo qqInfo , CommentVo commentVo) {
        try {
            bizCommentService.insertComment(qqInfo, commentVo);
        }catch (Exception e){
            return Result.success("评论失败，内容字符不合法");
        }
        return Result.success("评论成功，等待管理员审核");
    }

    /**
     * 获取评论
     * @return
     */
    @PostMapping("/comments")
    public Result comments(CommentVo commentVo) {
        PageInfo<BizComment> list = null;
        commentVo.setPageSize(PAGE_SIZE);
        try {
            list = bizCommentService.selectByCondition(commentVo);
        }catch (Exception e){
            return Result.error("加载数据失败");
        }
        return Result.success("加载数据成功").add("data", list);
    }


    /**
     * praise 文章点赞
     * @return
     */
    @PostMapping("/parise")
    public Result user(HttpServletRequest request) {
        try {
            bizArticleService.parise(request);
        } catch (CustomException e) {
            return Result.error(e.getMessage());
        }
        return Result.success("点赞成功");
    }


    /**
     * support 评论点赞
     * @return
     */
    @PostMapping("/support")
    public Result support(HttpServletRequest request) {
        try {
            bizCommentService.support(request);
        } catch (CustomException e) {
            return Result.error(e.getMessage());
        }
        return Result.success("点赞成功");
    }


    /**
     * support 评论踩
     * @return
     */
    @PostMapping("/oppose")
    public Result oppose(HttpServletRequest request) {
        try {
            bizCommentService.oppose(request);
        } catch (CustomException e) {
            return Result.error(e.getMessage());
        }
        return Result.success("点踩成功");
    }

    /**
     * 文章搜索
     * @return
     */
    @PostMapping("/search")
    public Result search(String content) {
        content = content.replaceAll(" ", "");
        List<BizArticle> bizArticles = bizArticleService.search(content);
        return Result.success("有结果").add("data", bizArticles);
    }

    /**
     * 申请友链
     */
    @PostMapping("/apply")
    public Result apply(SysLink sysLink) {
        try {
            sysLinkService.insert(sysLink);
        }catch (Exception e){
            e.printStackTrace();
            return Result.success("保存失败");
        }
        return  Result.success("提交成功，等待审核");
    }
}
